package com.lib.servlet.admin;

import com.alibaba.fastjson.JSON;
import com.lib.common.Constant;
import com.lib.entity.Admin;
import com.lib.entity.JsonResult;
import com.lib.service.AdminService;
import com.lib.service.ex.EmptyArgumentException;
import com.lib.service.ex.NotOldPwdException;
import com.lib.service.ex.RecordNotFoundException;
import com.lib.service.ex.ServiceException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "IsOldPwdServlet", value = "/admin/IsOldPwdServlet.do")
public class IsOldPwdServlet extends HttpServlet {
    private AdminService adminService = new AdminService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Admin admin = (Admin) request.getSession().getAttribute(Constant.SESSION_ADMIN);
        System.out.println("------name="+admin.getName());
        String opwd = request.getParameter("opwd");
        System.out.println("------opwd="+opwd);
        JsonResult jsonResult = null;

        try {
            adminService.isOldPwd(admin.getName(),opwd);
            jsonResult=JsonResult.getSuccessJR();
        } catch (EmptyArgumentException e) {
            jsonResult = new JsonResult(Constant.JSON_STATE_EMPTY_ARGUMENT,"参数不能为空");
        } catch (NotOldPwdException e) {
            jsonResult = new JsonResult(Constant.JSON_STATE_IS_NOT_OLD_PWD,"当前密码错误");
        } catch (RecordNotFoundException e) {
            jsonResult = new JsonResult(Constant.JSON_STATE_RECORD_NOT_FOUND,"用户不存在");
        } catch (ServiceException e) {
            e.printStackTrace();
            jsonResult = new JsonResult(Constant.JSON_STATE_SERVICE_ERROR,"系统异常");
        }
        System.out.println("----jsonResult="+ JSON.toJSONString(jsonResult));
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(JSON.toJSONString(jsonResult));
        response.getWriter().flush();
        response.getWriter().close();
    }
}
